package main

import (
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

// request
type StatsRequest struct {
	url     string
	headers map[string]string
	filter  Filter
	ff      interface{}
}

// filter
type Filter interface {
	filter(key string, value string) bool
}

type OutputFilter struct {
}

func (of OutputFilter) filter(key string, value string) bool {
	fmt.Println("of,key:" + key + ",value:" + value)
	return true
}

func (sr *StatsRequest) addFilter(filter Filter) {
	sr.filter = filter
}

func (sr StatsRequest) addHeader(key string, value string) {
	sr.headers[key] = value
}

func (sr StatsRequest) removeHeader(key string) {
	delete(sr.headers, key)
}

func (sr *StatsRequest) addFf(ff interface{}) {
	sr.ff = ff
}

func (sr StatsRequest) get() (result string, err error) {
	client := &http.Client{}
	req, err := http.NewRequest("GET", sr.url, nil)
	if err != nil {
		return "1", err
	}
	// 设置header
	for key, value := range sr.headers {
		// filter
		if sr.filter != nil {
			sr.filter.filter(key, value)
		}
		// ff
		if sr.ff != nil {
			sr.ff.(func(string, string))(key, value)
		}
		req.Header.Add(key, value)
	}
	resp, err := client.Do(req)
	if err != nil {
		return "2", err
	}
	defer func() {
		e := resp.Body.Close()
		if e != nil {
			panic(err)
		}
	}()
	var reader io.ReadCloser
	// 兼容gzip
	if resp.Header.Get("Content-Encoding") == "gzip" {
		reader, _ = gzip.NewReader(resp.Body)
	} else {
		reader = resp.Body
	}
	body, _ := ioutil.ReadAll(reader)
	return string(body), nil
}
